package operations;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class HibernateManager {
    private static HibernateManager inst = new HibernateManager();

    private SessionFactory sessionFactory;

    private ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<Session>();

    private HibernateManager() {
        Configuration cfg = new Configuration();
        cfg.configure();
        this.sessionFactory = cfg.buildSessionFactory();
    }

    public static HibernateManager instance() {
        return inst;
    }

    public void runCommand(final Runnable cmd) {
        Session session = this.sessionFactory.openSession();
        this.sessionThreadLocal.set(session);

        Transaction transaction;
        transaction = session.beginTransaction();
        try {
            cmd.run();
            session.flush();
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            throw new RuntimeException(e);
        } finally {
            this.sessionThreadLocal.set(null);
            session.close();
        }

    }

    public Session getSession() {
        return this.sessionThreadLocal.get();
    }

}
